package com.ly.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ly.entity.ShopType;
import com.ly.mapper.ShopTypeMapper;
import com.ly.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询所有商铺类别，用redis缓存
     * @return
     */
    @Override
    public List<ShopType> getList() {
        // 1. redis中有，直接返回
        String shopTypesJson = stringRedisTemplate.opsForValue().get("cache:shopTypes:");
        if(StrUtil.isNotBlank(shopTypesJson)){
            // 转为List
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypesJson, ShopType.class);
            return shopTypeList;
        }

        // 2. redis中没有，查询数据库，并写入redis
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        shopTypesJson = JSONUtil.toJsonStr(shopTypeList);
        stringRedisTemplate.opsForValue().set("cache:shopTypes:",shopTypesJson);
        return shopTypeList;
    }
}
